package com.zjitc.book.service.impl;

import com.zjitc.book.dto.UserDto;
import com.zjitc.book.entity.MyUserDetails;
import com.zjitc.book.entity.Permission;
import com.zjitc.book.entity.User;
import com.zjitc.book.mapper.UserMapper;
import com.zjitc.book.service.UserInfoService;
import com.zjitc.book.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserDetailsService, UserService, UserInfoService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

            User user = userMapper.getUserByUsername(username);
            if (user == null) {
                throw new UsernameNotFoundException("用户名不存在: " + username);
            }
            List<String> authorities = userMapper.getPermissionByUsername(username);

            //todo:查用户权限
            MyUserDetails myUserDetails = new MyUserDetails(user,authorities);
            return myUserDetails;
    }

    @Override
    public User register(UserDto userDto) {
        if (existsByUsername(userDto.getUsername())) {
            throw new RuntimeException("用户已存在");
        }
        User user = new User();
        user.setUsername(userDto.getUsername());
        user.setPassword(bCryptPasswordEncoder.encode(userDto.getPassword()));
        userMapper.addUser(user);
        return user;
    }

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.existsByUsername(username);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public List<Permission> getMenu() {
        // 获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof MyUserDetails) {
            // 从 MyUserDetails 对象中获取用户名
            MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            // 根据用户名查询菜单
            List<Permission> menu = userMapper.getMenu(username);
            System.out.println(menu);
            return menu;
        }
        // 如果认证信息为空或者 principal 不是 MyUserDetails 类型，返回空列表
        return new ArrayList<>();
    }

    private List<Permission> createTreeMenu(List<Permission> menus) {
        Map<Integer, Permission> menuMap = new HashMap<>();
        List<Permission> rootMenus = new ArrayList<>();

        // 首先将所有菜单放入 map 中
        for (Permission menu : menus) {
            menuMap.put(menu.getId(), menu);
        }

        // 构建树结构
        for (Permission menu : menus) {
            Integer parentId = menu.getParentid();
            if (parentId == 0) {
                rootMenus.add(menu);
            } else {
                Permission parentMenu = menuMap.get(parentId);
                if (parentMenu != null) {
                    if (parentMenu.getChildren() == null) {
                        parentMenu.setChildren(new ArrayList<>());
                    }
                    parentMenu.getChildren().add(menu);
                }
            }
        }
        return rootMenus;
    }
}
